<?php

namespace app\common\model;

use think\Image;
use think\Model;

class File extends Model
{
    public function add($data)
    {
        return $this->insertGetId($data);
    }


    //获取图片路劲
    public function getPath($id)
    {
        if (!is_int($id)){
            $id=explode(',',$id);
            $id=$id[0];
        }
        $detail = $this->where("id", $id)->find($id);
        return $detail['path'] ? getHost() . $detail['path'] : '';

    }



    //获取多张图片
    public function getPaths($ids)
    {
        $image_arr=[];
        if (empty($ids)){
            return $image_arr;
        }
        $ids=is_array($ids)?$ids:explode(',',$ids);
        foreach ($ids as $key=>$val){
            $image_arr[$key]['id']=$val;
            $image_arr[$key]['path']=$this->getPath($val);

        }

        return $image_arr;
    }

    //通过ID获取压缩图片路径
    public function getCompressImage($id, $width = 100, $height = 100)
    {
        $detail = $this->where("id", $id)->find($id);
        if ($detail && $detail['path']) {
            //原始路径
            $path = $detail['path'];
            //字符串总长度
            $length = strlen($path);
            //最后一个点的位置
            $dot = strrpos($path, '.');
            //图片前缀名称
            $name = substr($path, 0, $dot);
            $name = $name . '_' . $width . '_' . $height;
            //图片后缀（带点）
            $suffix = substr($path, $dot, $length - $dot);
            //完整路径
            $complete = $name.$suffix;
            if (file_exists('.'.$complete))
            {
                return getHost().$complete;
            }
            $image = Image::open('.'.$path);
            $image->thumb($width, $height)->save('.'.$complete);
            return getHost().$complete;
        }else{
            return '';
        }

    }

    //通过图片相对路径生成压缩图路径
    public function getCompressImageByPath($path, $width = 100, $height = 100)
    {
        //字符串总长度
        $length = strlen($path);
        //最后一个点的位置
        $dot = strrpos($path, '.');
        //图片前缀名称
        $name = substr($path, 0, $dot);
        $name = $name . '_' . $width . '_' . $height;
        //图片后缀（带点）
        $suffix = substr($path, $dot, $length - $dot);
        //完整路径
        $complete = $name.$suffix;
        if (file_exists('.'.$complete))
        {
            return getHost().$complete;
        }
        $image = Image::open('.'.$path);
        $image->thumb($width, $height)->save('.'.$complete);
        return getHost().$complete;
    }

    /**
     * 获取数组数据，组装成js需要
     * @param  [type] $ids [description]
     * @return [type]      [description]
     */
    public function getList($ids)
    {
        $list = $this->where('id', 'in', $ids)->field('*, title as name')->select()->each(function ($item, $key) {
            $item->url = model("File")->getPath($item->id, true);
        });
        return $list->toArray();
    }

    public function images_path($ids)
    {
        $list = $this->where('id', 'in', $ids)->field('id,path')->select()->each(function ($item, $key) {
            $item->path = $this->getCompressImage($item->id);
            $item->url = $this->getCompressImage($item->id);
            $item->path_origin = $this->getCompressImage($item->id);
            $item->url_origin = $this->getCompressImage($item->id);
        });
        return $list->toArray();
    }


    public function images_paths($ids)
    {
        $list = $this->where('id', 'in', $ids)->field('id,path')->select()->each(function ($item, $key) {
            $item->path = $this->getCompressImage($item->id);
            $item->url = $this->getCompressImage($item->id);
            $item->path_origin = model("File")->getPath($item->id, true);
            $item->url_origin = $this->getCompressImage($item->id);
        });
        return $list->toArray();
    }

    //删除图片，数据库和文件
    public function del($ids)
    {


        if (empty($ids)) {
            exception("请选择要删除的图片");
        }

        $where[] = ['id', 'in', $ids];
        $image_list = $this->where($where)->select();
        $res=true;
        if (!empty($image_list)) {
            foreach ($image_list as $key => $val) {

                if (empty($val['path'])){
                    $this->where(['id' => $val['id']])->delete();
                    return true;
                }

                if (file_exists('.' . $val['path'])) {
                    $res = unlink('.' . $val['path']);//删除原文件
                }

                $detail = $val;
                if ($detail && $detail['path']) {
                    //原始路径
                    $path = $detail['path'];
                    //字符串总长度
                    $length = strlen($path);
                    //最后一个点的位置
                    $dot = strrpos($path, '.');
                    //图片前缀名称
                    $name = substr($path, 0, $dot);
                    $name = $name . '_' . 100 . '_' . 100;
                    //图片后缀（带点）
                    $suffix = substr($path, $dot, $length - $dot);
                    //完整路径
                    $complete = $name . $suffix;

                    if (file_exists('.' . $complete)) {

                        unlink('.'.$complete);//有压缩图片则删除
                    }

                }

                $this->where(['id' => $val['id']])->delete();

            }

            if ($res) {
                return true;
            }

            return false;

        } else{
            exception('图片不存在');
        }
    }


    //通过ID获取压缩图片路径
    public function getCompressImages($image, $width = 100, $height = 100)
    {

        $detail =$image;
        if ($detail && $detail['path']) {
            //原始路径
            $path = $detail['path'];
            //字符串总长度
            $length = strlen($path);
            //最后一个点的位置
            $dot = strrpos($path, '.');
            //图片前缀名称
            $name = substr($path, 0, $dot);
            $name = $name . '_' . $width . '_' . $height;
            //图片后缀（带点）
            $suffix = substr($path, $dot, $length - $dot);
            //完整路径
            $complete = $name . $suffix;
            if (file_exists('.' . $complete)) {
                return getHost() . $complete;
            }else{
                if (file_exists('.'.$path)){
                    $image = Image::open('.' . $path);
                    $image->thumb($width, $height)->save('.' . $complete);
                    return getHost() . $complete;
                }else{
                    return '';
                }

            }


        } else {
            return '';
        }

    }



}
